import xlwings as xw
import json
import sys
import io


def createSheetIfNotExist(sheetName: str, wb, setBlack=False) -> object:
    """某个workbook是否存在名为sheetName的sheet

    Args:
        sheetName (str): 要查询的sheet的Name
        wb (object, optional): 该workbook. Defaults to wb0.
        setBlack (bool, optional): 设为黑色. Defaults to False.

    Returns:
        object: sheet对象
    """
    def handleSetBlack():
        if setBlack:
            # 该sheet的背景色改为黑色
            wb.sheets[sheetName].api.Tab.ThemeColor = 2
            wb.sheets[sheetName].api.Tab.TintAndShade = 0
    for sheet in wb.sheets:  # 遍历wb0的所有sheet
        if sheet.name == sheetName:  # 如果该sheet的名称与此相符
            handleSetBlack()
            return wb.sheets[sheetName]
    else:
        wb.sheets.add(sheetName)
        handleSetBlack()
        return wb.sheets[sheetName]


def receive():
    sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
    return json.loads(sys.stdin.read())


try:
    # app = xw.App(visible=False)
    options: dict = receive()
    # wb = xw.books.open(options["path"])
    # wb = app.books.open(options["path"])
    wb = xw.Book(options["path"])
    sheet = createSheetIfNotExist(options['sheetName'], wb)

    for item in options['data']:
        sheet[item["pos"]].value = item['value']

    wb.save()
    # wb.close()
finally:
    # print(json.dumps({}))
    try:
        wb.app.quit()
        app = xw.apps.active
        app.quit()
    finally:
        print(json.dumps({"success": True}))
